/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author ThinkGem
 */
import { watch, unref } from 'vue';
import { useI18n } from '/@/hooks/web/useI18n';
import { useTitle as usePageTitle } from '@vueuse/core';
import { useGlobSetting } from '/@/hooks/setting';
import { useRouter } from 'vue-router';

import { REDIRECT_NAME } from '/@/router/constant';

/**
 * Listening to page changes and dynamically changing site titles
 */
export function useTitle() {
  const { title } = useGlobSetting();
  const { t } = useI18n();
  const { currentRoute } = useRouter();

  const pageTitle = usePageTitle();

  watch(
    () => currentRoute.value.path,
    () => {
      const route = unref(currentRoute);

      if (route.name === REDIRECT_NAME) {
        return;
      }

      const tTitle = t(route?.meta?.title as string);
      pageTitle.value = tTitle ? ` ${tTitle} - ${title} ` : `${title}`;
    },
    { immediate: true },
  );
}

/**
 * 浏览器标题新消息闪动
 * @author ThinkGem
 */
export function useFlashTitle(message = '新消息', audioMessageId = 'audioMessage') {
  let blankMessage = '';
  for (let i = 0; i < message.length; i++) {
    blankMessage += '　';
  }

  let flashStep = 0;
  let flashTitleRun = false;
  let isWindowFocus = true;
  const origTitle = document.title;

  window.onfocus = function () {
    isWindowFocus = true;
  };
  window.onblur = function () {
    isWindowFocus = false;
  };

  function flashTitle() {
    if (isWindowFocus) {
      document.title = origTitle;
      flashTitleRun = false;
      return;
    }
    flashTitleRun = true;
    flashStep++;
    if (flashStep == 3) {
      flashStep = 1;
    }
    if (flashStep == 1) {
      document.title = '【' + message + '】' + origTitle;
    }
    if (flashStep == 2) {
      document.title = '【' + blankMessage + '】' + origTitle;
    }
    setTimeout(flashTitle, 500);
  }

  function doFlashTitle() {
    if (!flashTitleRun) {
      flashTitle();
    }
    const audioMessage = document.getElementById(audioMessageId) as HTMLAudioElement;
    if (audioMessage) {
      try {
        audioMessage.play();
      } catch (e) {}
    }
  }
  return doFlashTitle;
}
